#include<iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std; 
class Solution {
public:
    vector<vector<int>> threeSum(vector<int>& nums) {
        vector<vector<int>> ans;
        if (nums.size() < 3)return ans;
        sort(nums.begin(), nums.end());
        for (int i = 0; i < nums.size() - 2; i++)
        {
            if (i > 0 && nums[i] == nums[i - 1])continue;
            int z = i + 1, y = nums.size() - 1;
            while (z < y)
            {
                //cout << nums[i] << " " << nums[z] << " " << nums[y] << endl;
                if (nums[i] + nums[z] + nums[y] == 0)
                {
                    vector<int> temp;
                    temp.push_back(nums[i]);
                    temp.push_back(nums[z]);
                    temp.push_back(nums[y]);
                    ans.push_back(temp);
                }
                if (nums[i] + nums[z] + nums[y] > 0)
                {
                    while(z < y && nums[y]== nums[y-1])y--;
                    y--;
                }
                else 
                {
                    while (z < y && nums[z] == nums[z + 1])z++;
                    z++;
                }
            }
            
        }
        return ans;
    }
};
int main()
{
    vector<int> nums= { -1, 0, 1, 2, -1, -4 };
    Solution sol;
    vector<vector<int>> ans = sol.threeSum(nums);
    for (int i = 0; i < ans.size(); i++)
    {
        for (int j = 0; j < ans[i].size(); j++)
        {
            cout << ans[i][j] << " ";
        }
        cout << endl;
    }
}